package controllers

import (
	"encoding/json"
	"fmt"
	"io/ioutil"
	"net/http"

	"github.com/golang/glog"

	authapi "eccgateway/pkg/api/auth"
	nodeRegisterapi "eccgateway/pkg/api/nodeRegister"
	"eccgateway/pkg/services/nodeRegister"
	"eccgateway/pkg/util"
)

type NodeRegisterController struct {
}

func (c NodeRegisterController) Create(w http.ResponseWriter, r *http.Request) {
	info, err := util.GetUserInfo(r.Header.Get(authapi.ParseInfo))
	if err != nil {
		glog.Errorf("get user info from header failed, err: %v", err)
		util.ReturnErrorResponseInResponseWriter(w, http.StatusBadRequest, err.Error())
		return
	}

	requestBody, err := ioutil.ReadAll(r.Body)
	if err != nil {
		glog.Errorf("request body read failed, %v", err)
		util.ReturnErrorResponseInResponseWriter(w, http.StatusBadRequest, fmt.Sprintf("request body read failed, %v", err))
		return
	}

	req := nodeRegisterapi.Register{}
	err = json.Unmarshal(requestBody, &req)
	if err != nil {
		glog.Errorf("unmarshal request body failed, %v", err)
		util.ReturnErrorResponseInResponseWriter(w, http.StatusBadRequest, fmt.Sprintf("unmarshal request body failed, %v", err))
		return
	}

	err = validNodeRegisterCreateReqBody(req)
	if err != nil {
		glog.Errorf("create request body is invalid, %v", err)
		util.ReturnErrorResponseInResponseWriter(w, http.StatusBadRequest, fmt.Sprintf("%v", err))
		return
	}

	err = nodeRegister.GetRegisterService().AddRegisterNodeInCache(req, info)
	if err != nil {
		glog.Errorf("add register node in cache failed, %v", err)
		util.ReturnErrorResponseInResponseWriter(w, http.StatusInternalServerError, fmt.Sprintf("%v", err))
		return
	}
}

func validNodeRegisterCreateReqBody(req nodeRegisterapi.Register) error {
	if len(req.Node) == 0 {
		return fmt.Errorf("node name can't be empty")
	}

	typeIsExist := false
	for _, v := range nodeRegisterapi.AllowRegisterType {
		if req.Type == v {
			typeIsExist = true
			break
		}
	}
	if !typeIsExist {
		return fmt.Errorf("type is invalid")
	}

	devicePluginIsExist := false
	for _, v := range nodeRegisterapi.AllowRegisterDevicePlugin {
		if req.DevicePlugin == v {
			devicePluginIsExist = true
			break
		}
	}
	if !devicePluginIsExist {
		return fmt.Errorf("device plugin is invalid")
	}

	return nil
}
